<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 优惠券管理
 */
namespace app\allwin\controller;
use app\allwin\model\AllwinShop;
use app\allwin\model\Coupon as CouponModel;
use app\allwin\model\CouponSubsidize;
use app\allwin\model\CouponUser;
use app\allwin\model\Card;
use app\common\facade\Inform;
use think\facade\Request;
use think\helper\Time;
use app\allwin\model\AllwinStore;

class Coupon extends Common{

    public function initialize() {
        parent::initialize();
        $this->assign('pathMaps', [['name'=>'优惠券管理','url'=>url("coupon/index")]]);
    }

    /**
     * 列表
     */
    public function index(int $types = 0,int $page = 0){
        $condition = [];
        $time      = Request::param('time/d',0);
        $starttime = Request::param('starttime/s');
        $endtime   = Request::param('endtime/s');
        if($time){
            switch ($time) {
                case 2:
                    list($start, $end) = Time::yesterday();
                    break;
                case 30:
                    list($start, $end) = Time::month();
                    break;
                case 60:
                    list($start, $end) = Time::lastMonth();
                    break;
                default:
                    list($start, $end) = Time::today();
                    break;
            }
            $condition[] = ['create_time','>=',$start];
            $condition[] = ['create_time','<=',$end];
        }else{
            if($starttime){
                $condition[] = ['create_time','>=',strtotime($starttime)];
            }
            if($endtime){
                $condition[] = ['create_time','<=',strtotime($endtime)];
            }
        }
        $store_id   = Request::param('store_id/d');
        $store_name = Request::param('store_name');
        if($store_id){
            $condition[] = ['store_id','=',$store_id];
        }
        $keyword = Request::param('keyword');
        if(!empty($keyword)){
            $condition[] = ['name','like','%'.$keyword.'%'];
        }
        //统计
        $view['coupon_count']          = CouponModel::where($this->mini_program)->where($condition)->where(['is_end' => 0,'is_lock' => 0])->count();
        $view['coupon_end_count']      = CouponModel::where($this->mini_program)->where($condition)->where(['is_end' => 1])->count();
        $view['coupon_user_count']     = CouponUser::where($this->mini_program)->where($condition)->where(['is_end' => 0])->count();
        $view['coupon_user_end_count'] = CouponUser::where($this->mini_program)->where($condition)->where(['is_end' => 1])->count();
        switch ($types) {
            case 1:
                $condition[] = ['is_lock','=',1];
                $condition[] = ['is_end','=',0];
                break;
            case 2:
                $condition[] = ['is_lock','=',0];
                $condition[] = ['is_end','=',0];
                break;
            case 3:
                $condition[] = ['is_platform','=',1];
                $condition[] = ['is_end','=',0];
                break;
            case 4:
                $condition[] = ['is_end','=',1];
                break;
            default;
                $condition[] = ['is_end','=',0];
                break;
        }
        $view['lists']      = CouponModel::where($this->mini_program)->where($condition)->order('is_platform desc,sort desc,is_lock desc,update_time desc')->paginate(10,false,['query' => ['types' => $types,'store_id' => $store_id,'store_name' => $store_name]]);
        $view['types']      = $types;
        $view['page']       = $page;
        $view['keyword']    = $keyword;
        $view['store_id']   = $store_id;
        $view['store_name'] = $store_name;
        $view['time']       = $time;
        $view['starttime']  = $starttime;
        $view['endtime']    = $endtime;
        return view()->assign($view);
    }

    /**
     * 优惠券选项
     */
    public function selectId(){
        $view['store_id']    = $this->request->param('store_id/d',0);
        $view['input']       = $this->request->param('input/s');
        $view['keyword']     = $this->request->param('keyword');
        $view['is_platform'] = $this->request->param('is_platform/d',0);
        $view['is_lock']     = $this->request->param('is_lock/d',0);
        $view['is_check']    = $this->request->param('is_check/d',0);
        $view['is_shop']     = $this->request->param('is_shop/d',0);
        $condition   = [];
        $condition[] = ['is_lock', '=',$view['is_lock']];
        $condition[] = ['is_check','=',$view['is_check']];
        $condition[] = ['is_shop', '=',$view['is_lock'] ];
        $condition[] = ['is_platform','=',$view['is_platform'] ? 1 : 0];
        if($view['store_id']){
            $condition[] = ['store_id','=',$view['store_id']];
        }
        $view['lists'] = CouponModel::where($this->mini_program)->withSearch(['name'],['name' => $view['keyword']])->where($condition)->order('is_top desc,sort desc,is_lock desc,update_time desc')->paginate(10,false,['query' => ['keyword' => $view['keyword'],'store_id' => $view['store_id'],'input' => $view['input']]]);
        return view()->assign($view);
    }


    //优惠券预览和统计
    public function review(int $id,int $types = 0){
        $info = CouponModel::where($this->mini_program)->where(['id' => $id])->find();
        if(empty($info)){
            $this->error('内容不存在');
        }
        $info->weekday = json_decode($info->weekday,true);
        $condition = [];
        $condition['is_end']      = $types ?? 0;
        $condition['coupon_id']   = $id;
        $view['lists']            = CouponUser::where($this->mini_program)->where($condition)->order('id asc')->paginate(10,false,['query'=>['id' => $id,'types' => $types]]);
        $view['types']            = $types;
        $view['coupon_count']     = CouponUser::where($this->mini_program)->where(['coupon_id' => $id])->count();
        $view['coupon_end_count'] = CouponUser::where($this->mini_program)->where(['coupon_id' => $id,'is_end' => 1])->count();
        $view['coupon_size']      = CouponUser::where($this->mini_program)->where(['coupon_id' => $id])->sum('size');
        $coupon_user_size         = CouponUser::where($this->mini_program)->where(['coupon_id' => $id])->sum('user_size');
        $view['coupon_user_size'] = $view['coupon_size'] - $coupon_user_size;
        $view['info']             = $info;
        return view()->assign($view);
    }

    //编辑
    public function edit(){
        $id   = Request::param('id/d');
        if(request()->isAjax()){
            $data = [
                'id'         => Request::param('id/d'),
                'pay_price'  => Request::param('pay_price/f'),
                'shop_price' => Request::param('shop_price/f'),
                'theme'      => Request::param('theme/s'),
                'name'       => Request::param('name/s'),
                'img'        => Request::param('img/s'),
                'size'       => Request::param('size/f',0),
                'price'      => Request::param('price/f'),
                'weekday'    => Request::param('weekday/a',[]),
                'discount'   => Request::param('discount/d',0),
                'longtime'   => Request::param('longtime/d',0),
                'daynum'     => Request::param('daynum/d',0),
                'num'        => Request::param('num/d',0),
                'ontypes'    => Request::param('ontypes/d',0),
                'howmuch'    => Request::param('howmuch/d',0),
                'starttime'  => Request::param('starttime/s'),
                'endtime'    => Request::param('endtime/s'),
                'tips'       => Request::param('tips/s'),
                'types'      => Request::param('types/d',0),
            ];
            $validate = $this->validate($data,'Coupon.edit');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $data['weekday'] = json_encode(ids($data['weekday'],true));
            if($data['types'] == 0){
                $data['discount']  = 0;
            }else{
                $data['price'] = 0;
            }
            $data['starttime']   = strtotime($data['starttime']);
            $data['endtime']     = strtotime($data['endtime']);
            $data['is_check']    = 1;
            if($id){
                $data['id'] = $id;
                $result = CouponModel::where($this->mini_program)->where(['id' => $data['id']])->update($data);
            }else{
                $store_id = Request::param('store_id/d',0);
                $store = AllwinStore::where(['id' => $store_id])->find();
                if(empty($store)){
                    return json(['code'=>0,'msg'=>'商家必须选择']);
                }
                $data['member_miniapp_id'] = $this->member_miniapp_id;
                $data['create_time']       = time();
                $data['num_of']            = $data['num'];
                $data['update_time']       = time();
                $data['store_id']          = $store_id;
                $data['cate_id']           = $store->cate_id;
                $data['cate_sid']          = $store->cate_sid;
                $data['is_top']            = 0;
                $result                    = CouponModel::create($data);
            }
            if($result){
                return json(['code'=>200,'url'=>url('coupon/index',['page' => input('get.page/d')]),'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }else{
            $info = CouponModel::where($this->mini_program)->where(['id' => $id])->find();
            if(!empty($info)){
                $info->weekday = json_decode($info->weekday,true);
            }
            $view['info'] = $info;
            $view['page'] = input('get.page/d');
            return view()->assign($view);
        }
    }

    //删除
    public function delete(int $id){
        $rel = CouponModel::where(['id' => $id])->field('is_platform')->find();
        if($rel->is_platform == 1){
            return enjson(0,'超级券,禁止删除');
        }
        $result = CouponModel::where($this->mini_program)->where(['id' => $id])->delete();
        if($result){
            CouponSubsidize::where($this->mini_program)->where(['coupon_id' => $id])->delete();
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>403,'msg'=>'删除失败']);
        } 
    }

    /**
     * 排序
     */
    public function sort(){
        if(request()->isAjax()){
            $data = [
                'sort' => input('post.sort/d'),
                'id'   => input('post.id/d'),
            ];
            $validate = $this->validate($data,'Coupon.sort');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $result = CouponModel::where($this->mini_program)->where(['id' => $data['id']])->update(['sort'=>$data['sort']]);
            if($result){
                return json(['code'=>200,'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }
    }
   
    /**
     * 置顶/取消
     * @param integer $id 用户ID
     */
    public function isTop(int $id){
        $rel = CouponModel::where(['id' => $id])->field('is_top,is_platform')->find();
        $rel->is_top = $rel->is_top ? 0 : 1;
        if($rel->is_platform == 1 && $rel->is_top == 1){
            return enjson(0,'超级券,禁止设置推荐');
        }
        $rel->save();
        return json(['code'=>200,'msg'=>'操作成功']);
    } 

     /**
     * 审核和取消
     * @param integer $id 用户ID
     */
    public function isLock(int $id){
        $result = CouponModel::where(['id' => $id])->field('is_platform,is_lock,store_id')->find();
        $result->is_lock = $result->is_lock ? 0 : 1;
        if($result->is_platform == 1 && $result->is_lock == 1){
            return enjson(0,'超级券,禁止取消审核');
        }
        $rel = $result->save();
        if($rel){
            if($result->is_lock == 0){
                $store = AllwinStore::where('id','=',$result->store_id)->find();
                if($store){
                    Inform::sms($store->manage_uid,$this->member_miniapp_id,['title' =>'业务进展通知','type' => '优惠券申请','content' =>'您的优惠券申请已经通过审核','state' => '成功']);
                }
            }
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>0,'msg'=>'操作失败']);
        }
    } 
   
     /**
     * 设置默认
     * @param integer $id 用户ID
     */
    public function platform(int $id){
        $result = CouponModel::where(['id' => $id])->field('is_platform')->find();
        $result->is_platform = $result->is_platform ? 0 : 1;
        if($result->is_platform == 0){
            //简单平台券是否在其它地方使用
            $card = Card::where(['coupon_id' => $id])->count();
            if($card){
                return enjson(0,'在好店储值活动中有使用,禁止把优惠券设置为普通优惠券');
            }
        }else{
            $result->is_check = 0;
            $result->is_shop  = 0;
            AllwinShop::where($this->mini_program)->where(['coupon_id' => $id])->update(['coupon_id' => 0]);
        }
        $result->save();
        return json(['code'=>200,'msg'=>'操作成功']);
    }

  
    /**
     * 允许消费买单
     * @param integer $id 用户ID
     */
    public function isCheck(int $id){
        $rel = CouponModel::where(['id' => $id])->field('is_check,is_platform')->find();
        $rel->is_check = $rel->is_check ? 0 : 1;
        if($rel->is_platform == 1 && $rel->is_check == 1){
            return enjson(0,'超级券,禁止设置消费买单');
        }
        $rel->save();
        return json(['code'=>200,'msg'=>'操作成功']);
    } 

     /**
     * 允许优惠券铺子
     * @param integer $id 用户ID
     */
    public function isShop(int $id){
        $rel = CouponModel::where(['id' => $id])->field('is_shop,is_platform')->find();
        $rel->is_shop = $rel->is_shop ? 0 : 1;
        if($rel->is_platform == 1 && $rel->is_shop == 1){
            return enjson(0,'超级券,禁止设置允许单独领取');
        }
        $rel->save();
        return json(['code'=>200,'msg'=>'操作成功']);

    } 

    
     /**
     * 过期或失效回复
     * @param integer $id 用户ID
     */
    public function isEnd(int $id){
        $rel = CouponModel::where($this->mini_program)->where(['id' => $id])->field('id,is_end,num,endtime')->find();
        if(!$rel){
            return json(['code'=>0,'msg'=>'未找到资源']);
        }else{
            if($rel->num <= 0 ){
                return enjson(0,"禁止恢复,剩余数量【{$rel->num}】");
            }
            if($rel->endtime <= Time::today()[0]){
                return enjson(0,"禁止恢复,结束日期【".date('Y-m-d',$rel->endtime)."】");
            }
            $rel->is_end = 0;
            $rel->save();
            return json(['code'=>200,'msg'=>'操作成功']);
        }
    }
        

    /**
     * 用户已领优惠券管理
     *
     * @param integer $id  优惠券ID
     * @param integer $uid 用户ID
     * @return void
     */
    public function user(int $types = 0){
        $condition = [];
        $uid  = Request::param('uid/d');
        if($uid){
            $condition[] = ['uid','=',$uid];
        }
        $store_id   = Request::param('store_id/d');
        $store_name = Request::param('store_name/s');
        if($store_id){
            $condition[] = ['store_id','=',$store_id];
        }
        $time = Request::param('time/d',0);
        if($time){
            switch ($time) {
                case 2:
                    list($start, $end) = Time::yesterday();
                    break;
                case 30:
                    list($start, $end) = Time::month();
                    break;
                case 60:
                    list($start, $end) = Time::lastMonth();
                    break;
                default:
                    list($start, $end) = Time::today();
                    break;
            }
            $condition[] = ['create_time','>=',$start];
            $condition[] = ['create_time','<=',$end];
        }
        $starttime = Request::param('starttime/s');
        $endtime = Request::param('endtime/s');
        if($starttime){
            $condition[] = ['create_time','>=',strtotime($starttime)];
        }
        if($endtime){
            $condition[] = ['create_time','<=',strtotime($endtime)];
        }
        $view['coupon_size']      = CouponUser::where($this->mini_program)->where($condition)->sum("size");
        $view['coupon_user_size'] = CouponUser::where($this->mini_program)->where($condition)->sum("user_size");
        $view['coupon_user']      = $view['coupon_size']-$view['coupon_user_size'];
        $view['coupon_count']     = CouponUser::where($this->mini_program)->where($condition)->where(['is_end' => 0])->count();
        $view['coupon_end_count'] = CouponUser::where($this->mini_program)->where($condition)->where(['is_end' => 1])->count();
        $view['lists']      = CouponUser::where($this->mini_program)->where($condition)->where(['is_end'=>$types ? 1 : 0])->order('id desc')->paginate(20,false,['query'=>['uid' => $uid,'types' => $types,'starttime' => $starttime,'endtime' => $endtime,'time'=>$time]]);
        $view['types']      = $types;
        $view['time']       = $time;
        $view['starttime']  = $starttime;
        $view['endtime']    = $endtime;
        $view['uid']        = $uid;
        $view['store_id']   = $store_id;
        $view['store_name'] = $store_name;
        $view['pathMaps']   = [['name'=>'已领优惠券','url'=>url("coupon/user")]];
        return view()->assign($view);
    }

    /**
     * 查看用户优惠券信息
     * @param integer $id
     * @return void
     */
    public function userCoupon(int $id = 0){  
        $info = CouponUser::where($this->mini_program)->where(['id' => $id])->find();
        $info['weekday'] = weekdays(json_decode($info->weekday,true));
        $view['info'] = $info;
        return view()->assign($view);
    }

    /**
     * 删除用户的优惠券
     * @return void
     */
    public function deleteUser(int $id){
        $result = CouponUser::where($this->mini_program)->where(['id' => $id])->delete();
        if($result){
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>403,'msg'=>'删除失败']);
        }
    }
}